var areaCache = {}, defaultParent = "0";
var tabName = "good", navName = "all", cybercafeState = null, orderNumber = $("span[prop='orderNumber']");
var keyword = $("#keyword"), provinceid = $("#provinceid"), cityid = $("#cityid"), districtid = $("#districtid"), streetid = $("#streetid");
var goodContainer = $(".good-container");

$(function() {
	$(".weui-tabbar__item").click(function() {
		if (cybercafeState == null) {
			mobileGlobal.message("未能加载状态信息");
			return;
		}
		
		var $this = $(this), prop = $this.attr("prop");
		if (!cybercafeState && prop != "me") {
			mobileGlobal.message("注册信息未通过审核");
			return;
		}
		
		$this.addClass("weui-bar__item_on").siblings(".weui-bar__item_on").removeClass("weui-bar__item_on");
		$(".weui-tab__panel[prop='" + prop + "']").removeClass("hidden").siblings(".weui-tab__panel").addClass("hidden");
		
		switch (prop) {
			case "good":
				loadGood();
				break;
			case "order":
				loadOrder(navName);
				break;
			case "me":
				loadPersonalInfo();
				break;
			default:
				return;
		}
	});
	$("input[prop='areaSelector']").click(onAreaSelectorClick);
	$(".weui-navbar__item").click(function() {
		if (!cybercafeState) return;
		
		loadOrder($(this).attr("prop"));
	});
	
	var pageParams = mobileGlobal.getPageParams(), tempTabName = null, tempNavName = null;
	if (pageParams) {
		pageParams = eval("(" + pageParams + ")");
		tempTabName = pageParams.tabName;
		tempNavName = pageParams.navName;
	}
	
	mobileGlobal.sendRequest(__mobilectx + "/cybercafe/checkCybercafeState.xhtml", null, null, function(data, status) {
		mobileGlobal.hideLoading();
		
		if (!data.status) mobileGlobal.failed("加载数据失败");
		else {
			cybercafeState = data.result.cybercafeState;
			
			if (!data.result.cybercafeState) tabName = "me";
			else {
				if (tempTabName) tabName = tempTabName;
				else {
					if (data.result.orderNumber > 0) tabName = "order";
				}
				
				if (tabName === "order") {
					if (tempNavName) navName = tempNavName;
					else {
						if (data.result.orderNumber > 0) navName = "receiving";
					}
				}
				
				if (data.result.orderNumber > 0) orderNumber.text(data.result.orderNumber).removeClass("hidden");
			}
			
			$(".weui-tabbar__item[prop='" + tabName + "']").click();
		}
	});
});

//加载商品
function loadGood() {
	var data = {
		keyword : keyword.val(), 
		provinceid : provinceid.val() || null, 
		cityid : cityid.val() || null, 
		districtid : districtid.val() || null, 
		streetid : streetid.val() || null
	};
	
	mobileGlobal.sendRequest(__mobilectx + "/cybercafe/good/loadViewListData.xhtml", data, null, function(data, status) {
		if (data.status) {
			goodContainer.empty();
			
			for (var i = 0; i < data.result.length; i ++) {
				var supplier = data.result[i];
				
				var html = "<div class='supplier-item'><i class='fa fa-gift'></i>" + supplier.name + "</div>";
				goodContainer.append($(html));
				
				for (var j = 0; j < supplier.goods.length; j ++) {
					var good = supplier.goods[j];
					var html = "<div class='good-item' onclick='viewGood(\"" + good.goodid + "\");'>" + 
								"<img src='" + good.goodpic + "'>" + 
								"<div class='text'>" + 
									"<div class='name'>【" + good.goodcode + "】" + good.goodname + "</div>" + 
									"<div class='specs'>" + good.goodspecs + "</div>" + 
									"<div class='price'>￥<span class='number'>" + good.goodprice.toFixed(2) + "</span>元/<span>" + good.meteringunit + "</span></div>" + 
									"<div class='manufacturer'>" + good.manufacturer + "</div>" + 
									"<div class='operate'>" + 
										"<i class='fa fa-shopping-cart' onclick='addShoppingCart(\"" + good.goodid + "\");'></i>" + 
									"</div>" + 
								"</div>" + 
							   "</div>";
					goodContainer.append($(html));
				}
			}
			
			mobileGlobal.hideLoading();
		} else {
			mobileGlobal.hideLoading();
			mobileGlobal.failed("加载数据失败");
		}
	});
}

//浏览商品
function viewGood(goodid) {
	mobileGlobal.forward(__mobilectx + "/cybercafe/good/view.xhtml?goodid=" + goodid, true, "{'tabName' : 'good'}");
}

//添加购物车
function addShoppingCart(goodid) {
	var e = window.event || arguments.callee.caller.arguments[0];
	if (e.stopPropagation) {
		e.stopPropagation();
	} else e.cancelBubble = true;
	
	addToCart(goodid);
}

//加载订单
function loadOrder(prop) {
	var params = null;
	switch (prop) {
		case "all":
			params = {state : null};
			break;
		case "receiving":
			params = {state : sysGlobal.EntityState[8].value};
			break;
		case "completed":
			params = {state : sysGlobal.EntityState[9].value};
			break;
		case "cancelled":
			params = {state : sysGlobal.EntityState[10].value};
			break;
		default:
			return;
	}
	
	var $this = $("div.weui-navbar__item[prop='" + prop + "']");
	var orderContainer = $this.parent().siblings(".weui-tab__panel");
	
	if (!$this.hasClass("weui-bar__item_on")) {
		$this.addClass("weui-bar__item_on").siblings(".weui-bar__item_on").removeClass("weui-bar__item_on");
	}
	
	mobileGlobal.sendRequest(__mobilectx + "/cybercafe/order/loadOrderData.xhtml", params, null, function(data, status) {
		if (data.status) {
			orderContainer.empty();
			
			for (var i = 0; i < data.result.orders.length; i ++) {
				var order = data.result.orders[i];
				
				var ogHtml = "";
				for (var j = 0; j < order.ordergoods.length; j ++) {
					ogHtml += "<img src='" + order.ordergoods[j].goodpic + "'/>";
				}
				
				var btnHtml = "";
				switch (order.orderstate) {
					case 8:
						btnHtml = "<span class='button' prop='cancel'>取消订单</span>";
						break;
					case 9:
						btnHtml = "<span class='button' prop='receive'>确认收货</span>";
						break;
				}
				
				var oHtml = "<div class='order-item' prop='" + order.orderid + "'>" + 
								"<div class='top'>" + 
									"<div class='name'><i class='fa fa-gift'></i>" + order.entname + "</div>" + 
									"<div class='state'>" + sysGlobal.getEntityStateText(order.orderstate) + "</div>" + 
								"</div>" + 
								"<div class='middle'>" + 
									"<div class='left'>" + ogHtml + "</div>" + 
									"<div class='right'>" + 
										"<div class='total'>￥<span class='number'>" + order.ordertotal.toFixed(2) + "</span>元</div>" + 
										"<div class='count'>共" + order.ordergoods.length + "件</div>" + 
									"</div>" + 
								"</div>" + 
								"<div class='bottom'>" + btnHtml + "</div>" + 
							"</div>";
				var orderItem = $(oHtml);
				orderItem.click(viewOrderDetail);
				orderItem.find("span.button[prop='cancel']").click(cancelOrder);
				orderItem.find("span.button[prop='receive']").click(confirmReceive);
				
				orderContainer.append(orderItem);
			}
			
			if (data.result.handlingNumber > 0) {
				orderNumber.text(data.result.handlingNumber).removeClass("hidden");
			} else {
				orderNumber.text(0).addClass("hidden");
			}
			
			mobileGlobal.hideLoading();
		} else {
			mobileGlobal.hideLoading();
			mobileGlobal.failed("加载数据失败");
		}
	});
}

//查看订单详情
function viewOrderDetail() {
	var orderid = $(this).attr("prop"), navname = $("div.weui-navbar__item.weui-bar__item_on").attr("prop");
	mobileGlobal.forward(__mobilectx + "/cybercafe/order/detail.xhtml?orderid=" + orderid, true, "{'tabName' : 'order', 'navName' : '" + navname + "'}");
}

//取消订单
function cancelOrder() {
	var e = window.event || arguments.callee.caller.arguments[0];
	if (e.stopPropagation) {
		e.stopPropagation();
	} else e.cancelBubble = true;
	
	var $this = $(this), orderid = $this.parent().parent().attr("prop");
	
	mobileGlobal.openConfirmDialog("确定取消订单？", function() {
		mobileGlobal.closeConfirmDialog();
		
		mobileGlobal.sendRequest(__mobilectx + "/cybercafe/order/cancelOrder.xhtml", {orderid : orderid}, null, 
			function(data, status) {
				mobileGlobal.hideLoading();
				if (data.status) {
					mobileGlobal.openMessageDialog("取消订单成功！", function() {
						mobileGlobal.closeMessageDialog();
						$("div.weui-navbar__item.weui-bar__item_on").click();
					});
				} else {
					mobileGlobal.openMessageDialog(data.result, function() {
						mobileGlobal.closeMessageDialog();
					});
				}
			}, 
			function(xhr, msg, e) {
				mobileGlobal.hideLoading();
				mobileGlobal.openMessageDialog("网络请求错误！", function() {
					mobileGlobal.closeMessageDialog();
				});
			}
		);
	});
}

//确认收货
function confirmReceive() {
	var e = window.event || arguments.callee.caller.arguments[0];
	if (e.stopPropagation) {
		e.stopPropagation();
	} else e.cancelBubble = true;
	
	var $this = $(this), orderid = $this.parent().parent().attr("prop");
	
	mobileGlobal.openConfirmDialog("订单确定已收货？", function() {
		mobileGlobal.closeConfirmDialog();
		
		mobileGlobal.sendRequest(__mobilectx + "/cybercafe/order/confirmReceive.xhtml", {orderid : orderid}, null, 
			function(data, status) {
				mobileGlobal.hideLoading();
				if (data.status) {
					mobileGlobal.openMessageDialog("确认收货成功！", function() {
						mobileGlobal.closeMessageDialog();
						$("div.weui-navbar__item.weui-bar__item_on").click();
					});
				} else {
					mobileGlobal.openMessageDialog(data.result, function() {
						mobileGlobal.closeMessageDialog();
					});
				}
			}, 
			function(xhr, msg, e) {
				mobileGlobal.hideLoading();
				mobileGlobal.openMessageDialog("网络请求错误！", function() {
					mobileGlobal.closeMessageDialog();
				});
			}
		);
	});
}

//加载个人信息
function loadPersonalInfo() {
	mobileGlobal.sendRequest(__mobilectx + "/cybercafe/loadPersonalInfo.xhtml", null, null, function(data, status) {
		if (data.status) {
			var personalInfo = $(".personal-info");
			personalInfo.empty();
			
			switch (data.result.cybercafe.entitystate) {
			case 4:
				personalInfo.append($("<span>资料审核未通过，点击&nbsp;<a href='javascript:void(0);' onclick='resubmit();'>重新提交</a>&nbsp;资料！</span>"));
				break;
			case 5:
				personalInfo.append($("<span>资料审核中，请耐心等待！</span>"));
				break;
			case 6:
				personalInfo.append($("<span>资料已审核通过，更多功能敬请期待！</span>"));
				break;
			}
			
			mobileGlobal.hideLoading();
		} else {
			mobileGlobal.hideLoading();
			mobileGlobal.failed("加载数据失败");
		}
	});
}

//重新提交
function resubmit() {
	mobileGlobal.forward(__mobilectx + "/cybercafe/resubmit.xhtml", true, "{'tabName' : 'me'}");
}

//区域选择框点击事件
function onAreaSelectorClick() {
	var selector = $(this), selectorId = selector.attr("id"), selectorTitle = null, defaultValue = null, selectorData = null;
	
	var pvid = null, valueid = null;
	if (selectorId.startsWith("provinceid")) {
		valueid = "provinceid";
		selectorTitle = "请选择省份";
	} else if (selectorId.startsWith("cityid")) {
		pvid = "provinceid";
		valueid = "cityid";
		selectorTitle = "请选择城市";
	} else if (selectorId.startsWith("districtid")) {
		pvid = "cityid";
		valueid = "districtid";
		selectorTitle = "请选择区县";
	} else if (selectorId.startsWith("streetid")) {
		pvid = "districtid";
		valueid = "streetid";
		selectorTitle = "请选择街道";
	} else return;
	
	var parent = null;
	if (pvid == null) parent = defaultParent;
	else parent = $("#" + pvid).val();
	if (!parent) {
		mobileGlobal.message("请先选择上级区域");
		return;
	}
	
	defaultValue = $("#" + valueid).val();
	selectorData = areaCache[parent];
	if (!selectorData) {
		queryAreas(parent, selectorId, selectorTitle, defaultValue);
		return;
	}
	
	openAreaSelector(selectorId, selectorTitle, defaultValue, selectorData);
}

//查询区域
function queryAreas(parent, selectorId, selectorTitle, defaultValue) {
	var areaKey = defaultParent, data = null;
	if (parent && parent != defaultParent) {
		areaKey = parent;
		data = {parent : parent};
	}
	
	mobileGlobal.sendRequest(__ctx + "/nr/getAreasForSelect.xhtml", data, null, function(data, status) {
		mobileGlobal.hideLoading();
		if (data.status) {
			areaCache[areaKey] = data.result;
			if (selectorId) openAreaSelector(selectorId, selectorTitle, defaultValue, data.result);
		}
	});
}

//打开区域选择器
function openAreaSelector(id, title, value, data) {
	if (!data || !Array.isArray(data) || data.length == 0) {
		mobileGlobal.message("未找到任何区域");
		return;
	}
	
	var defaultValue = (value) ? [value] : [data[0].value];
	weui.picker(data, {
		id : id, 
		title : title, 
		defaultValue : defaultValue, 
		onConfirm : function(result) {
			onAreaSelected(this.id, result[0]);
		}
	});
}

//区域选择事件
function onAreaSelected(selectorId, selectedObject) {
	var selector = $("#" + selectorId);
	
	var valueid = null, children = null;
	if (selectorId.startsWith("provinceid")) {
		valueid = "provinceid";
		children = ["cityid", "districtid", "streetid"];
	} else if (selectorId.startsWith("cityid")) {
		valueid = "cityid";
		children = ["districtid", "streetid"];
	} else if (selectorId.startsWith("districtid")) {
		valueid = "districtid";
		children = ["streetid"];
	} else if (selectorId.startsWith("streetid")) {
		valueid = "streetid";
	} else return;
	
	var valuer = $("#" + valueid);
	if (valuer.val() != selectedObject.value) {
		valuer.val(selectedObject.value);
		selector.val(selectedObject.label);
		
		if (children == null) return;
		
		for (var index = 0; index < children.length; index ++) {
			var child = children[index];
			$("#" + child).val("");
			$("#" + child + "Selector").val("");
		}
		
		if (!areaCache[selectedObject.value]) queryAreas(selectedObject.value);
	}
}
